'use strict';

const { Service } = require('egg');
const uuidv1 = require('uuid/v1');

class StudentService extends Service {
  async getList(offset, limit) {
    const { ctx, app } = this;
    const db = app.mysql.get('spring');
    const pageCondition = {
      where: {},
      offset,
    };
    if (limit) {
      pageCondition.limit = limit;
    }
    const condition = Object.assign({}, pageCondition);
    let result = await db.select('t_student', condition);
    result = ctx.camelcaseKeys(result);
    return result;
  }

  async getCount() {
    const { app } = this;
    const db = app.mysql.get('spring');
    let sql = 'select count(*) as count from t_student';
    sql += ' where 1=1 ';
    const result = await db.query(sql);
    return result.length ? result[0].count : 0;
  }

  async create(student) {
    const { app } = this;
    const db = app.mysql.get('spring');
    const { name, birthday, linkman, phone, address, schoolId, gradeType, classname } = student;
    const studentId = uuidv1();
    try {
      const result = await db.insert('t_student', {
        student_id: studentId,
        name,
        birthday,
        linkman,
        phone,
        address,
        school_id: schoolId,
        grade_type: gradeType,
        classname,
      });
      return result;
    } catch (e) {
      return e;
    }
  }

}

module.exports = StudentService;
